<template>
    <div>
        <el-card>
            <el-form class="search" :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
                <el-form-item prop="timeTag">
                    <el-select v-model="queryParams.timeTag" size="small" style="width: 80px" @change="handleQuery">
                        <el-option :value="1" label="按秒"/>
                        <el-option :value="2" label="按分"/>
                        <el-option :value="3" label="按时"/>
                        <el-option :value="4" label="按日"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围" prop="dateRange">
                    <el-date-picker clearable size="small"
                                    v-model="queryParams.dateRange"
                                    type="datetimerange"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    range-separator="-"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    @change="handleQuery">
                    </el-date-picker>
                </el-form-item>
                <el-form-item prop="codes">
                    <el-select
                        v-model="queryParams.codes"
                        size="small"
                        multiple
                        collapse-tags
                        filterable
                        placeholder="请选择点位"
                        style="width: 200px;">
                        <el-option
                            v-for="row in cacheList"
                            :label="row.cacheDescr?row.cacheDescr:row.cacheCode"
                            :value="row.cacheCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    <el-button type="primary" icon="el-icon-setting" size="mini" @click="drawerOpen=true">图表设置</el-button>
                </el-form-item>
            </el-form>

            <el-drawer
                title="图表设置"
                :visible.sync="drawerOpen"
                direction="rtl"
                :show-close="false"
                :size="600"
                append-to-body>
                <el-form label-width="120px">
                    <el-form-item label="y轴坐标轴">
                        <table class="table">
                            <tr>
                                <th width="60px"></th>
                                <th width="50px">索引</th>
                                <th width="80px">位置</th>
                                <th>偏移</th>
                                <th>最小值</th>
                                <th width="100px">单位</th>
                            </tr>
                            <tr v-for="(row,index) in chartParam.yAxis">
                                <td>
                                    <el-button v-if="index==0" type="text" @click="addYAxis">添加</el-button>
                                    <el-button v-else type="text" @click="delYAxis(index)">删除</el-button>
                                </td>
                                <td>{{index}}</td>
                                <td class="input">
                                    <el-select v-model="row.position" style="width: 100%" @change="$forceUpdate()">
                                        <el-option value="left" label="左边"/>
                                        <el-option value="right" label="右边"/>
                                    </el-select>
                                </td>
                                <td class="input">
                                    <el-input-number v-model="row.offset" :controls="false" style="width: 100%;"/>
                                </td>
                                <td class="input">
                                    <el-input-number v-model="row.min" :controls="false" style="width: 100%;"/>
                                </td>
                                <td class="input">
                                    <el-select v-model="row.name" style="width: 100%" filterable allow-create
                                               @change="$forceUpdate()">
                                        <el-option value="°C" label="°C"/>
                                        <el-option value="A" label="A"/>
                                        <el-option value="m/s" label="m/s"/>
                                    </el-select>
                                </td>
                            </tr>
                        </table>
                    </el-form-item>
                    <el-form-item v-for="row in chartParam.codeMap" :label="row.name" v-if="row.status==1">
                        <el-select v-model="row.yAxisIndex" style="width: 100%" @change="$forceUpdate()">
                            <el-option v-for="(row,index) in chartParam.yAxis" :value="index" :label="`y轴索引${index}`"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="redrawChart()">重绘</el-button>
                    </el-form-item>
                </el-form>
            </el-drawer>

            <div ref="chart" style="height: calc(100% - 30px);border: 0px solid"></div>
        </el-card>
    </div>
</template>

<script>
    import {
        listCache,
        getHisChart
    } from '@/api/app/plc/cache'
    import * as echarts from 'echarts'

    export default {
        name: 'HisChart',
        components: {},
        data() {
            return {
                queryParams: {
                    dateRange: [this.moment().format('YYYY-MM-DD 00:00:00'), this.moment().add(1, 'd').format('YYYY-MM-DD 00:00:00')],
                    // dateRange: ['2023-02-27 00:00:00', '2023-02-27 02:00:00'],
                    timeTag: 1,
                    codes: []
                },
                cacheList: [],
                hisList: [],
                drawerOpen: false,
                chartParam: {
                    yAxis: [],
                    codeMap: {}
                }
            }
        },
        created() {
            this.getCacheList()
            window.addEventListener('resize', this.resizeChart)
        },
        destroyed() {
            window.addEventListener('resize', this.resizeChart)
        },
        methods: {
            getCacheList() {
                listCache({cacheIsSave: 1}).then(res => {
                    this.cacheList = res.data.rows
                    for (let i = 0; i < this.cacheList.length; i++) {
                        let row = this.cacheList[i]
                        this.chartParam.codeMap[row.cacheCode] = {
                            code: row.cacheCode,
                            name: row.cacheDescr ? row.cacheDescr : row.cacheCode,
                            yAxisIndex: 0,
                            status: 0
                        }
                    }
                    if (this.cacheList.length > 0) {
                        this.queryParams.codes.push(this.cacheList[0].cacheCode)
                        this.getList()
                    }
                })
            },
            getList() {
                let data = {
                    timeTag: this.queryParams.timeTag,
                    codes: this.queryParams.codes.join(',')
                }
                if (!this.queryParams.dateRange) {
                    this.queryParams.dateRange = [this.moment().format('YYYY-MM-DD 00:00:00'), this.moment().add(1, 'd').format('YYYY-MM-DD 00:00:00')]
                }
                if (this.queryParams.dateRange) {
                    data.startDt = this.queryParams.dateRange[0]
                    data.endDt = this.queryParams.dateRange[1]
                }
                getHisChart(data).then(res => {
                    this.hisList = res.data

                    //标记配置点位
                    for (let key in this.chartParam.codeMap) {
                        this.chartParam.codeMap[key].status = 0
                    }
                    for (let i = 0; i < this.hisList.length; i++) {
                        let row = this.hisList[i]
                        this.chartParam.codeMap[row.code].status = 1
                    }

                    this.drawHisChart(this.hisList)
                })
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1
                this.getList()
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm('queryForm')
                this.handleQuery()
            },
            drawHisChart() {
                let yAxis = this.chartParam.yAxis
                if (yAxis.length == 0) {
                    this.addYAxis()
                }
                for (let i = 0; i < yAxis.length; i++) {
                    yAxis[i].show = false
                }

                let series = []
                for (let i = 0; i < this.hisList.length; i++) {
                    let row = this.hisList[i]
                    let data = []
                    for (let j = 0; j < row.list.length; j++) {
                        let row2 = row.list[j]
                        data.push([row2.dt, row2.value])
                    }

                    //获取y轴索引
                    let yAxisIndex = 0
                    let config = this.chartParam.codeMap[row.code]
                    if (config) {
                        yAxisIndex = config.yAxisIndex
                    }
                    series.push({
                        code: row.code,
                        name: row.name,
                        type: 'line',
                        data: data,
                        symbolSize: 2,
                        showSymbol: false,
                        hoverAnimation: true,
                        yAxisIndex: yAxisIndex
                    })
                    yAxis[yAxisIndex].show = true
                }

                let dom = this.$refs.chart
                let chart = echarts.getInstanceByDom(dom)
                if (!chart) {
                    chart = echarts.init(dom, 'light')
                } else {
                    chart.resize()
                }
                let option = {
                    title: {
                        text: null
                    },
                    grid: {
                        top: 40,
                        left: 20,
                        right: 20,
                        bottom: 20,
                        containLabel: true
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            animation: false
                        }
                    },
                    legend: {},
                    dataZoom: [{
                        type: 'inside',
                    }],
                    xAxis: {
                        type: 'time'
                    },
                    yAxis: yAxis,
                    series: series
                }
                chart.setOption(option, true)
            },
            resizeChart() {
                this.drawHisChart()
            },
            addYAxis() {
                this.chartParam.yAxis.push({
                    type: 'value',
                    min: 0,
                    position: 'left',
                    offset: 0,
                    axisLine: {
                        show: true
                    },
                    axisTick: {
                        show: true
                    }
                })
            },
            delYAxis(index) {
                this.chartParam.yAxis.splice(index, 1)
                let maxIndex = this.chartParam.yAxis.length - 1
                for (let key in this.chartParam.codeMap) {
                    let row = this.chartParam.codeMap[key]
                    if (row.yAxisIndex > maxIndex) {
                        row.yAxisIndex = maxIndex
                    }
                }
            },
            redrawChart() {
                this.drawHisChart()
                this.msgSuccess('重绘完成')
            }
        }
    }
</script>
<style lang="scss" scoped>
    ::v-deep .el-drawer__body {
        padding: 0 20px;
    }

    .table {
        table-layout: fixed;
        border-collapse: collapse;
        width: 100%;
        text-align: center;
    }

    .table th, .table td {
        border: 1px solid #cccccc;
        padding: 0px 5px;
    }

    .table td.input {
        padding: 0;
    }

    ::v-deep {
        .el-card,.el-card__body {
            height: 100%;
        }
    }
</style>
